package uk.co.agileworks.bidpirate.web;

import java.util.Locale;

import javax.annotation.Resource;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import uk.co.agileworks.bidpirate.service.BusinessLogic;
import uk.co.agileworks.bidpirate.service.EbayFacade;

@Component
public class ControllerHelper {

	private static final Object[] ARGS = null;

	protected static final Logger LOGGER = LoggerFactory.getLogger(ControllerHelper.class);
	
	static final String ERROR_OBJECT = "error";
	static final String ERROR_VIEW = "error";

	@Autowired
	private BusinessLogic businessLogic;

	@Autowired
	private EbayFacade ebayFacade;

	@Autowired
	private UserSession userSession;

	@Resource
	private String openItemUrl;

	@Autowired
	private MessageSource messageSource;

	@ExceptionHandler
	public final ModelAndView handleException(Exception e) {
		LOGGER.error(e.toString());
		LOGGER.debug(ExceptionUtils.getStackTrace(e));
		ModelAndView modelAndView = new ModelAndView(ERROR_VIEW);
		modelAndView.addObject(ERROR_OBJECT, e);
		modelAndView.addObject("message", 
				messageSource.getMessage(e.getMessage(), ARGS, e.toString(), Locale.getDefault()));
		return modelAndView;
	}

	public final BusinessLogic getBusinessLogic() {
		return businessLogic;
	}

	public final EbayFacade getEbayFacade() {
		return ebayFacade;
	}

	public final String getOpenItemUrl() {
		return openItemUrl.replace("%EBAY_HOME%", userSession.getUser().getRegion().getEbayHome());
	}

	public final UserSession getUserSession() {
		return userSession;
	}

}
